/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 * 
 */
package seedpod.webapp.view.seedpodwidgets;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;

import seedpod.exceptions.InvalidWidgetException;
import seedpod.exceptions.SeedpodException;
import seedpod.kb2db.ClsMap;
import seedpod.kb2db.SlotMap;
import seedpod.model.AVPair;
import seedpod.model.InstanceRelationship;
import seedpod.model.NoObjectFoundException;
import seedpod.model.ProtegeValueType;
import seedpod.model.SeedpodDO;
import seedpod.model.SeedpodModel;
import seedpod.model.SeedpodModel.RdbCls.FormWidget;
import seedpod.model.SeedpodModel.RdbCls.ViewWidget;
import seedpod.rdb.PMFactory;
import seedpod.rdb.PManager;
import seedpod.webapp.view.htmlwidget.HtmlLink;
import seedpod.webapp.view.htmlwidget.Image;
import seedpod.webapp.view.htmlwidget.ImageButton;
import seedpod.webapp.view.htmlwidget.Table;

public class SpreadSheet extends Object_Link {

	public static ImageButton btnRemoveRelationship() {
		ImageButton btn = new ImageButton( "removeInstance", "image/Remove.gif", "", "remove relationship" );
		btn.inactivate();
		return btn;
	}

	public SpreadSheet() {
	// TODO Auto-generated constructor stub
	}

	public SpreadSheet(AVPair avpair) {
		super( avpair );
		// _toClassName = InstanceRelationship.getTargetClassName( getAttribute() );
	}

	private void addRowValue( SeedpodDO obj, Vector<SlotMap> attributes, Table instanceTable ) {
		Image instanceIcon = new Image( "instanceIcon", "image/Instance.gif" );

		SlotMap att;

		for ( int a = 0; a < attributes.size(); a++ ) {
			att = attributes.elementAt( a );
			if ( att.getProtegeValueType().equals( ProtegeValueType.Instance ) ) {
				Object val = obj.getAVPair( att ).getStringValue();

				if ( att.getName().compareTo( SeedpodModel.RdbSlot.THING_ID ) == 0 )
					instanceTable.addCell( new HtmlLink( "#", /*
															 * DisplayInstance.constructUrl(
															 * obj.getOid(),obj.getMetaCls().getName(),
															 */
					instanceIcon.render() + "(" + obj.getOid() + ")" ) );
				else if ( val != null )
					instanceTable.addCell( val );
				else instanceTable.addCell( "" );

			} else {
				InstanceRelationship rel = (InstanceRelationship)obj.getAVPair( att ).getValue();
				ArrayList<Object> targets = rel.getTargetObjects();
				SeedpodDO target = (SeedpodDO)targets.get( 0 );
				if ( obj != null ) if ( target.getOid() == _relationship.getSourceOid() )
					instanceTable.addCell( "" );
				else if ( att.isMultiple() ) // TODO IMPLEMENT see more
						instanceTable.addCell( "#"/* new HTMLLink(DisplayInstance.constructUrl( obj ), "...") */);
					else instanceTable.addCell( Object_Link.objectLink( target ) );
			}

		}
	}

	public ImageButton btnAddRelationship() {
		// can only browse and then add from existing object if the from_object's reference
		// to the to_object is NOT required

		// EMSClass fromCls = _relationship.getSourceEMSClass();
		// EMSClass toCls = _relationship.getTargetEMSClass();
		// Vector attDependency = toCls.getDependency();
		//
		ImageButton btn = new ImageButton( "addRelationship", "image/Add.gif", "", "add from existing " + getAttribute().getAllowedCls() );
		if ( !getAttribute().isMultiple() && _toObjOids.size() > 0 ) btn.inactivate();

		String redirect = "#"; /*
								 * RelateInstanceForm.constructURL( _relationship. getSourceEMSClassName(),
								 * _relationship.getSourceObjectId(), getAttribute().getAttributeName(),
								 * DisplayInstance.constructUrl( _relationship.getSourceObject() ) );
								 */

		btn.addJavascript( "onClick=\"if (this.form != null){this.form.action+='" + "&redirect=" + redirect + "'; this.form.submit();} else { window.location='" + redirect + "&redirect='+this.document.URL; }\"" );
		return btn;
	}

	public ImageButton btnCreateInstance() {
		String createURL = "#";
		// String createURL = RelateNewInstanceForm.constructURL( _relationship.
		// getSourceEMSClassName(),
		// _relationship.getSourceObjectId(), getAttribute().getAttributeName()
		// );

		ImageButton btn = new ImageButton( "create", "image/Create.gif", createURL, "create and add new " + getAttribute().getAllowedCls() );
		if ( _relationship.getSourceOid() == SeedpodDO.UNKNOWN_OID ) btn.inactivate();
		if ( !getAttribute().isMultiple() && _toObjOids.size() > 0 ) btn.inactivate();

		return btn;
	}

	@Override
	public FormWidget getFormWidgetType() {
		return null;
	}

	@Override
	public ViewWidget getViewWidgetType() {
		return ViewWidget.SPREADSHEET;
	}

	@Override
	protected Table instanceTable() {

		Table instanceTable = new Table( "instanceCollection" );
		instanceTable.setAlternativeRowColor( true );
		instanceTable.setTableCellSpacing( 2, 4 );

		if ( _relationship != null ) {
			String toClsName = _relationship.getTargetClassName();
			ClsMap toCls = _relationship.getTargetClass();
			Collection<SlotMap> toClsAttributes = toCls.getSlotMaps();

			// print column headings
			// instanceTable.addCellComponent( "" );

			// add table column header
			Vector<SlotMap> columnHeading = new Vector<SlotMap>();
			SlotMap thisAtt;
			String header;
			instanceTable.addRow();
			for ( SlotMap slotMap : toClsAttributes ) {
				thisAtt = slotMap;
				header = thisAtt.getName();

				if ( header != null && thisAtt.getDisplayName().trim().length() > 0 ) {
					instanceTable.addCell( thisAtt.getDisplayName() );
					columnHeading.add( thisAtt );
				}
			}

			PManager manager;
			try {
				manager = PMFactory.getInstance().createManager();
			} catch (SeedpodException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return instanceTable;
			}

			SeedpodDO tmpObj;
			Integer tmpOid;
			for ( int oCount = 0; oCount < _toObjOids.size(); oCount++ ) {
				tmpOid = _toObjOids.get( oCount );
				instanceTable.addRow();

				try {
					tmpObj = new SeedpodDO( toClsName, tmpOid.intValue(), manager );
					addRowValue( tmpObj, columnHeading, instanceTable );
				} catch (NoObjectFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return instanceTable;
	}

	@Override
	public String render() {
		try {
			validateWidget();
		} catch (InvalidWidgetException e) {
			renderErrorComment( e.getMessage() );
		}
		// return "spreadsheet";
		String view = "";
		// box around the collection box
		view += "<div " + ATT( "style", "border:1px solid gray; padding: 0px; background-color:white;" ) + ">";

		// menu buttons div
		view += "<div " + ATT( "id", "collectionMenu" ) + ATT( "style", "background-color: #eeeeff;padding:3;" ) + ">";
		view += btnCreateInstance().render() + "&nbsp;";
		view += btnAddRelationship().render() + "&nbsp;";
		view += btnRemoveRelationship().render() + "&nbsp;";
		view += "(Class= " + /* EMSSchema.getClass( _toClassName ).getUserAssignedName() + */")";
		view += "</div>";

		view += instanceTable().render();
		view += "</div>";

		return view;
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		if ( !getAttribute().isRelationship() || !getAttribute().isMultiple() )
			throw new InvalidWidgetException( "Spreadsheet handles only instance relations or set data." );
	}
}